//
//  DayThreeViewController.m
//  LockTest
//
//  Created by ZhangBo on 2018/12/4.
//  Copyright © 2018 ZhangBo. All rights reserved.
//

#import <ReactiveObjC/ReactiveObjC.h>
#import <NSObject+RACKVOWrapper.h>

#import "DayThreeViewController.h"
#import "KFC.h"
#import "BlueView.h"
#import "HKRunloop.h"
#import "HKThread.h"

@interface DayThreeViewController ()
@property(weak, nonatomic) IBOutlet BlueView *blueView;
@property(weak, nonatomic) IBOutlet UIButton *btn;
@property(weak, nonatomic) IBOutlet UITextField *textField;
@property(assign, nonatomic) BOOL finished;
@property(nonatomic, strong) dispatch_source_t timer;

@property(weak, nonatomic) IBOutlet UIButton *reSendBtn;
@property(assign, nonatomic) int time;
@property(nonatomic, strong) RACDisposable *disposable;
@property(nonatomic, strong) RACSignal *signal;
@end

@implementation DayThreeViewController

- (void)dealloc {
    NSLog(@"来了");
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self test_rac4];

}

// 最常见的应用场景:字典转模型!!
- (void)sequence_demo4 {
    //解析plist文件
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"kfc.plist" ofType:nil];
    NSArray *dictArr = [NSArray arrayWithContentsOfFile:filePath];

//    NSMutableArray * arr = [NSMutableArray array];
//    [dictArr.rac_sequence.signal subscribeNext:^(NSDictionary * x) {
//        KFC * kfc = [KFC kfcWithDict:x];
//        [arr addObject:kfc];
//    }];
    //更加爽的用法
    //会将一个集合中的所有元素都映射成一个新的对象!
    NSArray *arr = [[dictArr.rac_sequence map:^id _Nullable(NSDictionary *value) {
        //返回模型!!
        return [KFC kfcWithDict:value];
    }] array];
    NSLog(@"%@", arr);
}

- (void)sequence_demo3 {
    //字典
    NSDictionary *dict = @{@"name": @"hank", @"age": @"18"};
    //字典转集合
    [dict.rac_sequence.signal subscribeNext:^(RACTuple *x) {
//        NSString * key = x[0];
//        NSString * value = x[1];
//        NSLog(@"%@%@",key,value);
        //RACTupleUnpack:用来解析元祖
        //宏里面的参数,传需要解析出来的变量名称
        // = 右边,放需要解析的元祖
        RACTupleUnpack(NSString *key, NSString *value) = x;
        NSLog(@"%@ : %@", key, value);
    }];
}

- (void)sequence_demo2 {
    //数组
    NSArray *arr = @[@"abc", @"bbb", @123];

    //RAC集合
//    RACSequence * requence = [arr rac_sequence];
//    //遍历
//    RACSignal * signal = [requence signal];
//
//    //订阅信号
//    [signal subscribeNext:^(id  _Nullable x) {
//        NSLog(@"%@",x);
//    }];

    [arr.rac_sequence.signal subscribeNext:^(id _Nullable x) {
        NSLog(@"%@", x);
    }];
}

- (void)sequence_demo1 {
    //元祖
    RACTuple *tuple = [RACTuple tupleWithObjectsFromArray:@[@"aaa", @"bbb", @123]];
    NSString *str = tuple[0];
    NSLog(@"%@", str);
}

//RACSequence:用于代替NSArray,NSDictionary,可以使用快速的遍历
- (void)test_rec1 {
    [self sequence_demo1];
    [self sequence_demo2];
    [self sequence_demo3];
    [self sequence_demo4];
}

- (void)event_demo5 {
    //5.监听文本框
    [_textField.rac_textSignal subscribeNext:^(NSString *_Nullable x) {
        NSLog(@"%@", x);
    }];
}

- (void)event_demo4 {
    //4.代替通知
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillShowNotification object:nil] subscribeNext:^(NSNotification *_Nullable x) {
        NSLog(@"%@", x);
    }];
}

- (void)event_demo3 {
    //3.监听事件
    [[_btn rac_signalForControlEvents:(UIControlEventTouchUpInside)] subscribeNext:^(__kindof UIControl *_Nullable x) {
        NSLog(@"%@", x);
    }];
}

- (void)event_demo2 {
    //2.代替KVO
    [_blueView rac_observeKeyPath:@"frame" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew observer:nil block:^(id value, NSDictionary *change, BOOL causedByDealloc, BOOL affectedOnlyLastComponent) {
        //回调
        NSLog(@"value%@---%@", value, change);

    }];

    //更爽!!!
//    [[_blueView rac_valuesForKeyPath:@"frame" observer:nil] subscribeNext:^(id  _Nullable x) {
//        NSLog(@"%@",x);
//
//    }];
}

- (void)event_demo1 {
    //1.代替代理:RACSubject
    [[_blueView rac_signalForSelector:@selector(btnClick:)] subscribeNext:^(RACTuple *_Nullable x) {
        NSLog(@"%@", x);
    }];
}

- (void)test_rac2 {

    [self event_demo5];
}

- (void)test_rac3 {
    //事件 交给谁处理的??  Runloop!
    //Runloop模式 && 多线程!!
    //NSDefaultRunLoopMode 默认模式;
    //UITrackingRunLoopMode UI模式:只能被UI事件唤醒!!
    //NSRunLoopCommonModes  占位模式:默认&UI模式


//    [NSTimer scheduledTimerWithTimeInterval:1.0 target:self   selector:@selector(timerMethod) userInfo:nil repeats:YES];
    HKThread *thread = [[HKThread alloc] initWithBlock:^{
        NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
        //开启runloop循环
        [[NSRunLoop currentRunLoop] run];

        NSLog(@"come here!!%@", [NSThread currentThread]);//a  b
    }];

    [thread start];
}

- (void)timerMethod {
    if (_finished) {
        [NSThread exit];
    }
    NSLog(@"来了%@", [NSThread currentThread]);//1  2
}

- (void)test_rac4 {
    //GCD设置timer
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));

    //GCD的事件单位是纳秒
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0);

    dispatch_source_set_event_handler(timer, ^{
        NSLog(@"-----_%@", [NSThread currentThread]);
    });

    //启动
    dispatch_resume(timer);
    _timer = timer;
}

- (void)timerDemo {
    //RAC tiemr 让你上瘾!!
    [[RACSignal interval:1.0 onScheduler:[RACScheduler scheduler]] subscribeNext:^(NSDate *_Nullable x) {
        NSLog(@"%@", [NSThread currentThread]);
    }];
}

//发送验证码按钮点击 HomeViewController present
- (IBAction)reSendClick:(id)sender {
    //改变按钮状态
    self.reSendBtn.enabled = NO;
    //设置倒计时
    self.time = 10;
    //每一秒进来
    self.signal = [RACSignal interval:1.0 onScheduler:[RACScheduler mainThreadScheduler]];

    self.disposable = [self.signal subscribeNext:^(NSDate *_Nullable x) {
        NSLog(@"%@", self);
        //时间先减少!
        self->_time--;
        //设置文字
        NSString *btnText = self->_time > 0 ? [NSString stringWithFormat:@"请等待%d秒", self->_time]
            : @"重新发送";
        [self.reSendBtn setTitle:btnText forState:self->_time > 0 ? (UIControlStateDisabled) : (UIControlStateNormal)];
        //设置按钮
        if (self->_time > 0) {
            self->_reSendBtn.enabled = NO;
        } else {
            self->_reSendBtn.enabled = YES;
            //取消订阅!!
            [self->_disposable dispose];
        }
    }];
}

- (void)test_rac5 {
    [self.disposable dispose];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
//    _finished = YES;
}

@end
